package org.pwwong.scalautils.signals

import org.pwwong.scalautils.event.Event

object ConstantSignal{
  def apply[A](_value:A):ConstantSignal[A] = new ConstantSignal(_value)
}

class ConstantSignal[+T](protected val value:T) extends Signal[T] {
  override val onChange:Event[T] = new Event[T]{
    override def bind[U>:T](boundedEvent:Event[U]):Event[T] = this
    override def unbind[U>:T](boundedEvent:Event[U]):Event[T] = this
    override def apply(ref:AnyRef)(runMe:T=>Any):Event[T] = this
    override def removeListener(key:AnyRef):Event[T] = this
    override def fire[U>:T](eventData:U):Unit = {}
  }
  override def apply() = value
}

abstract class Signal[+T] {
  val onChange:Event[T] = Event[T]
  def onChangeAndOnce(ref:AnyRef)(runMe:T=>Any):Event[T] = { runMe(apply()); onChange(ref)(runMe) }
  def onAnyChange(ref:AnyRef)(runMe: =>Any):Event[T] = { onChange(ref){tmp => runMe} }
  def onAnyChangeAndOnce(ref:AnyRef)(runMe: =>Any):Event[T] = { runMe; onAnyChange(ref)(runMe) }
  
  def apply():T
}
